# Please install OpenAI SDK first: `pip3 install openai`
# sk-d4d06b347b774b2fa4fb35a20d892eed
import requests
import json
import datetime

# 配置API密钥和基础URL
api_key = 'sk-d4d06b347b774b2fa4fb35a20d892eed'
base_url = 'https://api.deepseek.com'

# 构建请求头
headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': f'Bearer {api_key}'
}


def send_request(user_input):
    # 设置请求参数（如果有）
    data = {
        "model": "deepseek-chat",
        "messages": [
            {
                "role": "system",
                "content": "你的名字叫做小虎得力助手,你是一个全能的助手，能够精准解答用户的问题"
            },
            {
                "role": "user",
                "content": user_input
            }
        ],
        "stream": True  # 启用流式传输
    }

    # 发送POST请求
    response = requests.post(f'{base_url}/chat/completions', headers=headers, json=data, stream=True)

    # 检查响应状态码
    if response.status_code == 200:
        dt1 = datetime.datetime.now()
        print(f"时间：{dt1.year}年{dt1.month}月{dt1.day} {dt1.hour}时{dt1.minute}分{dt1.second}秒")
        # 逐行处理流式响应
        for line in response.iter_lines():
            if line:
                decoded_line = line.decode('utf-8')
                if decoded_line.startswith("data:"):
                    try:
                        json_data = json.loads(decoded_line[5:])
                        content = json_data['choices'][0]['delta'].get('content', '')
                        if content:
                            print(content, end='', flush=True)
                    except json.JSONDecodeError:
                        pass
        print('\n------------- 分界线 ----------------')  # 换行
    else:
        print(f'请求失败，状态码: {response.status_code}')
        print(f'响应内容: {response.text}')
        return None


def main():
    print("欢迎使用数加小虎对话系统！输入'退出'以结束对话。")
    while True:
        # 获取用户输入
        user_input = input("你: ")

        # 检查是否退出
        if user_input.lower() == '!exit':
            print("道友，有缘江湖见！")
            break

        # 发送请求并获取响应
        send_request(user_input)


if __name__ == "__main__":
    main()
